<?php

namespace App\Http\Controllers\Backend\Content;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use App\Interfaces\CategoryInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CategoryController extends BaseController
{
    public function __construct(CategoryInterface $category)
    {
        $this->category = $category;
    }

    public function getCategory(int $id): JsonResponse
    {
        $res = $this->category->getCategory($id);
        if (!$res){
            return $this->apiResult(['code'=>1,'message'=>'暂无数据！']);
        }
        return $this->apiResult(['code'=>0,'data'=>$res,'message'=>'success！']);
    }

    public function getCategories(Request $request): JsonResponse
    {
        $loginUser = $request->get('userInfo');
        $tenantId = $loginUser['userId'];
        $cates = $this->category->getAllCategory($tenantId);
        return $this->apiResult(['code'=>0,'data'=>$cates,'message'=>'SUCCESS']);
    }

    public function updateCategory(Request $request): JsonResponse
    {
        $data = $request->input();
//        $data['disabled'] = $data['menuType']===0?1:0;
        $data['updateTime'] = dateTime();
        $res = $this->category->updateCategory($data);
        if (!$res){
            return $this->apiResult(['code'=>1,'message'=>'修改失败！']);
        }
        return $this->apiResult(['code'=>0,'message'=>'修改成功！']);
    }

    public function addCategory(Request $request): JsonResponse
    {
        $data = $request->input();
        $loginUser = $request->get('userInfo');
        $tenantId = $loginUser['userId'];
        $data['tenantId'] = $tenantId;
        $data['disabled'] = $data['menuType']===0?1:0;
        $data['createTime'] = dateTime();
        $res = $this->category->addCategory($data);
        if (!$res){
            return $this->apiResult(['code'=>1,'message'=>'添加失败！']);
        }
        return $this->apiResult(['code'=>0,'message'=>'添加成功！']);
    }

    public function deleteCategory(int $id): JsonResponse
    {
        $data['deleted'] = 1;
        $data['updateTime'] = dateTime();
        $data['cateId'] = $id;
        $res = $this->category->updateCategory($data);
        if (!$res){
            return $this->apiResult(['code'=>1,'message'=>'删除失败！']);
        }
        return $this->apiResult(['code'=>0,'message'=>'删除成功！']);
    }
}
